package a202110.day13;

/**
 * 反转字符串中的单词 III
 * <p>
 * 给定一个字符串，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
 * <p>
 * 输入："Let's take LeetCode contest"
 * 输出："s'teL ekat edoCteeL tsetnoc"
 * <p>
 * 提示:
 * 在字符串中，每个单词由单个空格分隔，并且字符串中不会有任何额外的空格。
 *
 * @author yousj
 * @since 2021/10/31
 */
public class Main02 {

    public static void main(String[] args) {
        System.out.println(Integer.valueOf(' '));
        System.out.println(reverseWords("Let's take LeetCode contest"));
        System.out.println(reverseWords1("Let's take LeetCode contest"));
        System.out.println(reverseWords2("Let's take LeetCode contest"));
    }

    private static String reverseWords(String s) {
        int len = s.length();
        char[] chars = s.toCharArray();
        int l = 0;
        for (int i = 0; i < len; i++) {
            if (chars[i] == 32 || i == len - 1) {
                if (i == len - 1) i++;
                for (int j = 0; j < (i - l) >> 1; j++) {
                    char tmp = chars[i - 1 - j];
                    chars[i - 1 - j] = chars[l + j];
                    chars[l + j] = tmp;
                }
                l = i + 1;
            }
        }
        return new String(chars);
    }

    private static String reverseWords1(String s) {
        String[] split = s.split(" ");
        for (int i = 0; i < split.length; i++) {
            split[i] = new StringBuffer(split[i]).reverse().toString();
        }
        return String.join(" ", split);
    }

    private static String reverseWords2(String s) {
        int len = s.length();
        char[] chars = s.toCharArray();
        int l = 0;
        for (int i = 0; i < len; i++) {
            if (chars[i] == 32 || i == len - 1) {
                if (i == len - 1) i++;
                for (int j = 0; j < (i - l) >> 1; j++) {
                    int x = l + j, y = i - 1 - j;
                    chars[x] ^= chars[y];
                    chars[y] ^= chars[x];
                    chars[x] ^= chars[y];
                }
                l = i + 1;
            }
        }
        return new String(chars);
    }
}
